﻿var Manager = {
	consts:null,
	windows: null,
	control: null,
	container: null,
	initialize: function(q){
		ScriptLoader.Load("/js/fckeditor.js");

		var xmlhttp = new HTTPRequest(true, true, false);
		xmlhttp.send("/" + bloger + "/mysort.xml", null, function(r) {
			window.docs.sort = r.getXML();
		});
		$id("syblog_manager_loader_text").innerHTML = "正在加载用户数据，请稍候……&nbsp;";
		var xmlhttp1 = new HTTPRequest(true, true, true);
		xmlhttp1.send("/const.xml", null, function(r1) {
			$id("syblog_manager_loader_text").innerHTML = "正在加载用户界面，请稍候……&nbsp;";
			var xmlhttp2 = new HTTPRequest();
			xmlhttp2.send(
				"/ui/common/manager.xml",
				null,
				function(r2){
					this.container = document.createElement("div");
					this.container.className = "manager_container";
					var control = this.createControl();
	
					var frame = $id("syblog_manager_frame");
	
					frame.appendChild(control);
					frame.appendChild(this.container);
	
					this.windows = new Object();
					var define = r2.getXML().documentElement;
	
					control.appendChild(this.createMenu(define.selectSingleNode("menu")));
	
					var ws = define.selectNodes("window");
					for(var i = 0;i < ws.length;i++) {
						var wid = "$___window___" + ws[i].getAttribute("id");
						this.windows[wid] = document.createElement("div");
						with(this.windows[wid])
						{
							className = "syblog_window";
	
							var right_bar = document.createElement("div");
							right_bar.className = "syblog_window_right_bar";
							appendChild(right_bar);
	
							var close_btn = document.createElement("a");
							close_btn.href = "#";
							close_btn.className = "syblog_window_close_button";
							close_btn.onclick = function(){
								this.parentNode.parentNode.style.display="none";
								return event.returnValue = !(event.cancelBubble = true);
							}
							right_bar.appendChild(close_btn);
	
							var window_title = document.createElement("div");
							window_title.className = "syblog_window_title";
							window_title.innerHTML = '<span class="left"></span><span>{0}</span><span class="right"></span>'.format(ws[i].getAttribute("title"));
							right_bar.appendChild(window_title);
							$(window_title).bindDragTo(right_bar.parentNode);
	
							var window_body = document.createElement("div");
							with(window_body) {
								className = "syblog_window_body";
								innerHTML = '<br/>' + ws[i].text.trim();
								removeChild(firstChild);
							}
							right_bar.appendChild(window_body);
	
							var window_footer = document.createElement("div");
							window_footer.className = "syblog_window_footer";
							window_footer.innerHTML = '<span class="left"></span><span class="right"></span>';
							right_bar.appendChild(window_footer);
	
							var window_shadow = document.createElement("div");
							window_shadow.className = "syblog_window_shadow";
							window_shadow.style.width = (parseInt(ws[i].getAttribute("width")) + 2) + "px";
							window_shadow.style.height = (parseInt(ws[i].getAttribute("height")) + 2) + "px";
							window_shadow.innerHTML = "<iframe></iframe>";
							appendChild(window_shadow);
							
							style.width = right_bar.style.width = window_body.style.width = ws[i].getAttribute("width") + "px";
							style.height = right_bar.style.height = ws[i].getAttribute("height") + "px";
							window_body.style.height = (parseInt(ws[i].getAttribute("height")) - 22) + "px";
						}
					}
					frame.style.display = "block";
					$id("syblog_manager_loader").style.display = "none";
				}.bind(this)
			);
			this.buildConstData(r1.getXML());
		}.bind(this));
		
	},
	buildConstData: function(constDom) {
		this.consts = new Object();
		var constNodes = constDom.documentElement.selectNodes("node");
		for(var i = 0;i < constNodes.length;i++) {
			this.addConst(constNodes[i]);
		}
	},
	addConst: function(cst) {
		this.addClasss(this.consts[cst.getAttribute("id")] = [], cst.selectNodes("node"));
	},
	addClasss: function(cst,clss) {
		for(var i = 0;i < clss.length;i++) {
			var cls = new Object();
			cst.push(cls);
			this.addClass(cls,clss[i]);
		}
	},
	addClass: function(cls,clsNode) {
		cls.id = clsNode.getAttribute("id");
		cls.name = clsNode.getAttribute("name");
		this.addClasss(cls.items = [], clsNode.selectNodes("node"));
	},
	createControl: function() {
		var control = document.createElement("div");
		control.className = "manager_control";
		var closeBtn = document.createElement("div");
		closeBtn.className = "manager_control_close";
		control.appendChild(closeBtn);
		var btn = document.createElement("a");
		btn.href = "#";
		btn.hideFocus = true;
		btn.onclick = function(){
			$id("syblog_manager_frame").style.display="none";
			return event.returnValue = !(event.cancelBubble = true);
		};
		closeBtn.appendChild(btn);
		return control;
	},
	createMenu: function(cfg) {
		var menu = document.createElement("div");
		menu.className = "manager_menu";
		var groups = cfg.selectNodes("group");
		for(var i = 0;i < groups.length;i++) {
			var group = document.createElement("dl");
			
			var gtitle = document.createElement("dt");
			var tc = document.createElement("span");
			tc.innerHTML = groups[i].getAttribute("name");
			gtitle.appendChild(tc);
			
			gtitle.onclick = function() {
				toggleDl(this);
			}
			group.appendChild(gtitle);
			
			var contain = document.createElement("dd");
			contain.appendChild(this.createMenuItem(groups[i]));
			group.appendChild(contain);
			
			var footer = document.createElement("dd");
			footer.className = "syblog_group_footer";
			group.appendChild(footer);
			
			menu.appendChild(group);
		}
		return menu;
	},
	createMenuItem:function(group) {
		var entity = document.createElement("ul");
		var items = group.selectNodes("item");
		for(var i = 0;i < items.length;i++) {
			var item = document.createElement("li");
			var btn = document.createElement("a");
			btn.href = "#";
			btn.handler = items[i].getAttribute("handler");
			btn.id = "$___window___" + items[i].getAttribute("mapping");
			btn.innerHTML = items[i].getAttribute("name");
			btn.onclick = function() {
				if(Manager.open(this.id) && this.handler != null) {
					eval(this.handler);
				}
				return event.returnValue = !(event.cancelBubble = true);
			};
			item.appendChild(btn);
			entity.appendChild(item);
		}
		return entity;
	},
	open: function(maping) {
		function queue(win) {
			var zIdx = win.style.zIndex;
			var wins = win.parentNode.childNodes;
			for(var i = 0;i < wins.length;i++) {
				if(wins[i].style.zIndex > zIdx) {
					wins[i].style.zIndex = (win.style.zIndex = wins[i].style.zIndex) - 1;
				}
			}
			win.style.zIndex = win.parentNode.childNodes.length + 1;
		}
		
		var win = this.windows[maping];	
		win.style.display = "block";
		if(!this.container.contains(win)) {
			this.container.appendChild(win);
			win.onmousedown = function(){
				queue(this);
			}
			with(win.style) {
				zIndex = this.container.childNodes.length + 1;
				left = Math.floor(Math.max($id('syblog_body').offsetWidth - parseInt(width), 0) / 2) + "px";
				top = Math.floor(Math.max($id('syblog_body').offsetHeight - parseInt(height), 0) / 2) + "px";
			}
			return !(event.returnValue = !(event.cancelBubble = true));
		}
		else {
			queue(win);
			return event.returnValue = !(event.cancelBubble = true);
		}
	},
	createWriter: function() {
		var f = $('manager_topic_writeform');
		f.onValidateFail = function() {
			this.elements['publicBth'].disabled = this.elements['saveBth'].disabled = false;
		}
		f.editor = new FCKeditor( 'topiccontent','739','500' ) ;
		f.editor.ToolbarSet = 'Bloger';
		f.editor.ReplaceTextarea();
		var sorts = window.docs.sort.documentElement.selectNodes("body/a[@id!='0']");
		var sort = $(f.elements['sort']);
		sort.options.length = sorts.length;
		for(var i = 0;i < sorts.length;i++) {
			sort.options[i].text = sorts[i].text;
			sort.options[i].value = sorts[i].getAttribute('id');
		}
		with($(f.elements['class'])) {
			var category = this.consts["category"];
			for(var i = 0;i < category.length;i++) {
				options.length = category.length;
				for(var i = 0;i < category.length;i++) {
					options[i].value = category[i].id;
					options[i].text = category[i].name;
				}
			}
			selectedIndex = 0;
		}
		f.elements['class'].onchange();
	},
	associateList: function(dl, ass, src) {
		var css = this.consts[src][dl.selectedIndex].items;
		with(dl.form.elements[ass]) {
			options.length = css.length;
			for(var i = 0;i < css.length;i++) {
				options[i].value = css[i].id;
				options[i].text = css[i].name;
			}
			selectedIndex = 0;
		}
	},
	saveTopic: function(f, p, reset) {
		if(f.editor.GetState() != FCK_EDITMODE_WYSIWYG) {
			alert("对不起，请先切换到设计模式再保存！");
			return;
		}
		if(p != null) {
			f.elements['public'].value = p;
		}
		f.elements['content'].value = f.editor.GetXHTML(true);
		f.elements['publicBth'].disabled = f.elements['saveBth'].disabled = true;
		f.post(function(){
			if(f.elements['public'].value == "true") {
				var xmlhttp = new HTTPRequest(true, true, false);
				xmlhttp.send("/" + bloger + "/sort/" + f.elements['sort'].value + ".xml");
				var xmlhttp2 = new HTTPRequest(true, true, false);
				xmlhttp2.send("/" + bloger + "/sort/0.xml");
				if(!reset && f.elements['publiced'].value == "true") {
					var xmlhttp3 = new HTTPRequest(true, true, false);
					xmlhttp3.send("/" + bloger + "/topic/" + f.elements['id'].value);
				}
			}
			f.elements['publicBth'].disabled = f.elements['saveBth'].disabled = false;
			alert("文章保存成功");
			if(reset) {
				f.editor.SetHTML("");
				f.elements['title'].value = f.elements['tags'].value = f.elements['summary'].value = f.elements['quote'].value = "";
			}
			if($id("manager_topic_list")) {
				Manager.getTopicList(1);
			}
		},
		function(r) {
			f.elements['publicBth'].disabled = f.elements['saveBth'].disabled = false;
		});
	},
	loadSorts: function() {
		var f = $('manager_sort_form');
		$id("manager_sort_list").appendChild(f.list = document.createElement("ul"));
		f.list.selectedIndex = 0;
		f.list.onchange = function(){
			f.elements["name"].value = window.docs.sort.documentElement.selectNodes("body/a")[this.selectedIndex + 1].text;
		}
		f.list.onclick = function() {
			if(event.srcElement.tagName == "LI" && event.srcElement.nodeIndex != this.selectedIndex) {
				this.childNodes[this.selectedIndex].className = "";
				this.childNodes[this.selectedIndex = event.srcElement.nodeIndex].className = "selected";
				this.onchange();
			}
		}
		with(f.list) {
			var sorts = window.docs.sort.documentElement.selectNodes("body/a[@id!='0']");
			for(var i = 0;i < sorts.length;i++) {
				var option = document.createElement("li");
				appendChild(option);
				option.nodeIndex = i;
				option.innerText = sorts[i].text;
			}
			
			childNodes[0].className = "selected";
		}
		f.list.onchange();
	},
	setSort:function(f,active) {
		var idx = f.list.selectedIndex;
		var sortName = f.elements["name"].value.trim();
		var sortID = window.docs.sort.documentElement.selectNodes("body/a")[idx + 1].getAttribute("id");
		var wf = $id("manager_topic_writeform");
		var ef = $id("manager_topic_editform");
		var mts = $id("manager_topiclist_sort");
		
		var xmlhttp = new HTTPRequest();
		var dat = "active=" + active + "&sort=" + sortID + "&name=" + encodeURIComponent(sortName);
		switch(true) {
			case (active == 0 && sortName.length > 0):
				xmlhttp.send("/SetSort.aspx", dat, function(r) {
					sortID = r.getText();
					var node = window.docs.sort.createElement("a");
					node.setAttribute("id", sortID);
					node.setAttribute("href", "/" + bloger + "/sort/" + sortID + ".xml");
					node.text = sortName;
					window.docs.sort.documentElement.selectSingleNode("body").appendChild(node);
					
					
					var option = document.createElement("li");
					f.list.childNodes[f.list.selectedIndex].className = "";
					f.list.appendChild(option);
					option.className = "selected";
					f.list.selectedIndex = option.nodeIndex = f.list.childNodes.length - 1;
					option.innerText = sortName;
					
					f.list.onchange();
					
					if(wf != null) {
						with(wf.elements["sort"]){
							options.add(new Option(sortName, sortID));
						}
					}
					if(ef != null) {
						with(ef.elements["sort"]){
							options.add(new Option(sortName, sortID));
						}
					}
					if(mts != null){
						mts.options.add(new Option(sortName, sortID));
					}
				});
				break;
			case (active == 1 && sortName.length > 0):
				xmlhttp.send("/SetSort.aspx", dat, function() {
					f.list.childNodes[idx].innerText = sortName;
					window.docs.sort.documentElement.selectNodes("body/a")[idx + 1].text = f.list.childNodes[idx].innerText = sortName;
					if(wf != null) {
						with(wf.elements["sort"]){
							options[idx].text = sortName;
						}
					}
					if(ef != null) {
						with(ef.elements["sort"]){
							options[idx].text = sortName;
						}
					}
					if(mts != null){
						mts.options[idx + 1].text = sortName;
					}
				});
				break;
			case (active < 2 && sortName.length == 0):
				alert("请输入栏目名称");
				break;

			case (active == 2 && idx == 0) :
				alert("不能删除默认栏目");
				break;
			case (active == 2) && confirm("如果删除栏目则该栏目下的所有日志将自动转移到默认栏目，真的要删除该栏目吗？"):
				xmlhttp.send("/SetSort.aspx", dat, function() {
					var body = window.docs.sort.documentElement.selectSingleNode("body")
					body.removeChild(body.selectNodes("a")[idx + 1]);
					
					if(wf != null) {
						with(wf.elements["sort"]){
							remove(idx);
						}
					}
					if(ef != null) {
						with(ef.elements["sort"]){
							remove(idx);
						}
					}
					if(mts != null){
						mts.remove(idx + 1);
					}
					
					var li = f.list.childNodes[idx];
					var next = li;
					while(next = next.nextSibling) {
						next.nodeIndex -= 1;
					}
					
					if(f.list.selectedIndex == idx) {
						if(li.nextSibling) {
							li.nextSibling.className = "selected";
						}

						else {
							li.previousSibling.className = "selected";
							f.list.selectedIndex -= 1;
						}
						f.list.removeChild(li);
						f.list.onchange();
					}
					else if(f.list.selectedIndex > idx) {
						f.list.removeChild(li);
						f.list.selectedIndex -= 1;
					}
					else {
						f.list.removeChild(li);
					}
				});
				break;
		}
	},
	loadTopics: function() {
		var sorts = window.docs.sort.documentElement.selectNodes("body/a");
		with($("manager_topiclist_sort")) {
			options.length = sorts.length;
			for(var i = 0;i < sorts.length;i++) {
				options[i].text = sorts[i].text;
				options[i].value = sorts[i].getAttribute('id');
			}
			options[0].text = "所有栏目";
		}
		Manager.getTopicList(1);
	},
	getTopicList: function(p) {
		var list = $id("manager_topic_list");
		var xmlhttp = new HTTPRequest(true, false, true);
		if(!list.styleshheet) {
			xmlhttp.send("/ui/common/m-topic-list.xsl", null, function(r) {
				list.styleshheet = r.getXML();
				Manager.getTopicList(p);
			});
		}
		else {
			var data	= "bloger=" + bloger
						+ "&size=20&state=" + $id("manager_topiclist_state").value
						+ "&sort=" + $id("manager_topiclist_sort").value
						+ "&page=" + p;
			xmlhttp.send("/DataReader.aspx?ds=topiclist", data, function(r) {
				list.innerHTML = r.getXML().transformNode(list.styleshheet);
			});
		}
	},
	editTopic: function(id) {
		if(Manager.open('$___window___editor')) {
			var f = $('manager_topic_editform');
			f.onValidateFail = function() {
				this.elements['publicBth'].disabled = this.elements['saveBth'].disabled = false;
			}
			f.editor = new FCKeditor( 'editcontent','739','500' ) ;
			f.editor.ToolbarSet = 'Bloger';
			f.editor.ReplaceTextarea();
			var sorts = window.docs.sort.documentElement.selectNodes("body/a[@id!='0']");
			var sort = $(f.elements['sort']);
			sort.options.length = sorts.length;
			for(var i = 0;i < sorts.length;i++) {
				sort.options[i].text = sorts[i].text;
				sort.options[i].value = sorts[i].getAttribute('id');
			}
			with($(f.elements['class'])) {
				var category = this.consts["category"];
				for(var i = 0;i < category.length;i++) {
					options.length = category.length;
					for(var i = 0;i < category.length;i++) {
						options[i].value = category[i].id;
						options[i].text = category[i].name;
					}
				}
				selectedIndex = 0;
			}
			f.elements['class'].onchange();
		}
		var xmlhttp = new HTTPRequest();
		xmlhttp.send("/DataReader.aspx?ds=topic", "id=" + id, function(r) {		
			var rde = r.getXML().documentElement;
			var f = $('manager_topic_editform');
			f.elements["publicBth"].disabled = f.elements["saveBth"].disabled = true;
			
			var tn = rde.selectSingleNode("table/row");
			
			f.elements["id"].value = id;
			f.elements["title"].value = tn.selectSingleNode("title").text;
			f.elements["summary"].value = tn.selectSingleNode("summary").text;
			f.elements["hometop"].checked = (tn.selectSingleNode("hometop").text == "true");
			f.elements["sorttop"].checked = (tn.selectSingleNode("sorttop").text == "true");
			f.elements["quote"].value = tn.selectSingleNode("quote").text;
			f.elements["publiced"].value = f.elements["public"].value = tn.selectSingleNode("state").text;
			with(f.elements["sort"]) {
				value = tn.selectSingleNode("sort").text;
			}
			var cls = tn.selectSingleNode("class").text;
			f.elements["class"].value = cls.substring(0, cls.length - 2);
			f.elements["class"].onchange();
			f.elements["class2"].value = cls;
			var tagns = rde.selectNodes("table[2]/row/*");
			var tags = [];
			for(var i = 0;i < tagns.length;i++) {
				tags.push(tagns[i].text);
			}
			f.elements["tags"].value = tags.join(' ');
			f.elements["publicBth"].style.display = (tn.selectSingleNode("state").text == "true" ? "none" : "");
			
			var tbcount = parseInt(tn.selectSingleNode("trackback").text);
			if(tbcount > 0) {
				var xmlhttp2 = new HTTPRequest(true,true,false);
				xmlhttp2.send("/" + bloger + "/topic/" + id + "/trackback.xml", null, function(r) {
					var trackbacks = r.getXML().documentElement.selectNodes("body/p");
					var html = ['<div class="manager_trackback_head"><div class="manager_trackback_title">标题</div><div class="manager_trackback_bloger">博客名称</div><div class="manager_trackback_time">引用时间</div></div>'];
					for(var i = 0;i < trackbacks.length;i++) {
						var link = trackbacks[i].selectSingleNode("a");
						html.push('<div class="manager_trackback_body"><div class="manager_trackback_title"><a target="_blank" href="');
						html.push(link.getAttribute("href"));
						html.push('" title="');
						html.push(trackbacks[i].selectSingleNode("pre").text.replace(/"/mg, "&quot;"));
						html.push('">');
						html.push(link.text.parseHTML());
						html.push('</a></div><div class="manager_trackback_bloger">');
						html.push(link.getAttribute("title").parseHTML());
						html.push('</div><div class="manager_trackback_time">');
						html.push(trackbacks[i].getAttribute("time"));
						html.push('</div><div class="manager_trackback_button">');
						html.push('<a href="#" onclick="Manager.deleteTrackBack(this,\'');
						html.push(id + '\','+ i);
						html.push(');return false">删除</a></div></div>');
					}
					$id("manager_external_trackback").innerHTML = html.join('');
				});
			}
			else {
				$id("manager_external_trackback").innerHTML = "没有外部引用记录";
			}
			
			var ccount = parseInt(tn.selectSingleNode("comment").text);
			if(ccount > 0) {
				Manager.showComment(id, 1, Math.ceil(ccount / 30));
			} else {
				$id("manager_external_comment").innerHTML = "没有评论记录";
			}
			
			var xmlhttp2 = new HTTPRequest(true, true, false);
			xmlhttp2.send("/" + bloger + "/topic/" + id, null, function(r) {
				f.elements["publicBth"].disabled = f.elements["saveBth"].disabled = false;
				var de = r.getXML().documentElement;
				try {
					f.editor.SetHTML(f.elements["content"].value = de.selectSingleNode("body").text);
				}
				catch(ex) {
					f.elements["content"].value = de.selectSingleNode("body").text;
				}
				finally {
					f.elements["nocomment"].checked = (de.getAttribute("nocomment") == 1);
				}
			});
			
			try {
				f.editor.SetHTML("正在加载日志正文，请稍候......");
			}
			catch(ex) {
				f.elements["content"].value = "正在加载日志正文，请稍候......";
			}
		});
	},
	showComment: function(topic, page, max) {
		var xmlhttp = new HTTPRequest(true,false,false);
		xmlhttp.send("/" + bloger + "/topic/" + topic + "/" + page + ".xml",null,function(r) {
			var comments = r.getXML().documentElement.selectNodes("body/div");
			var html = ['<div class="manager_trackback_head"><div class="manager_trackback_title">评论</div><div class="manager_trackback_bloger">作者</div><div class="manager_trackback_time">发表时间</div></div>'];
			for(var i = 0;i < comments.length;i++) {
				html.push('<div class="manager_trackback_body"><div class="manager_trackback_title">');
				if(comments[i].getAttribute("deleted") != null) {
					html.push('<span style="text-decoration:line-through">已删除</span>');
				}
				else {
					html.push('<span title="');
					html.push(comments[i].text.replace(/"/mg, "&quot;"));
					html.push('">');
					html.push(comments[i].text.parseHTML());
					html.push('</span>');
				}
				html.push('</div><div class="manager_trackback_bloger">');
				if(comments[i].getAttribute("id") != null) {
					html.push('<a href="/');
					html.push(comments[i].getAttribute("id"));
					html.push('" title="');
					html.push(comments[i].getAttribute("name").replace(/"/mg, "&quot;"));
					html.push('" target="_blank">');
					html.push(comments[i].getAttribute("name").parseHTML());
					html.push('</a>');
				}
				else {
					html.push('<span title="');
					html.push(comments[i].getAttribute("name").replace(/"/mg, "&quot;"));
					html.push('">');
					html.push(comments[i].getAttribute("name").parseHTML());
					html.push('</span>');
				}
				html.push('</div><div class="manager_trackback_time">');
				html.push(comments[i].getAttribute("time"));
				html.push('</div>');
				if(comments[i].getAttribute("deleted") == null) {
					html.push('<div class="manager_trackback_button"><a href="#" onclick="Manager.deleteComment(this,\'');
					html.push(topic + '\',' + page + ',' + i);
					html.push(');return false">删除</a></div>');
				}
				html.push('</div>');
			}
			if(max > 1) {
				html.push('<div class="syblog_pager"><div class="syblog_pager_right_bar"><div class="syblog_pager_header_bar"><span class="left"></span><span class="right"></span></div><div class="syblog_pager_content">');
					
				var start = Math.max(page - 5, 1);
				var end = Math.min(start + 5,max);
				function appendItem(pager, p, txt) {
					pager.push('<a href="#" onclick="Manager.showComment(\'');
					pager.push(topic);
					pager.push("',");
					pager.push(p);
					pager.push(',');
					pager.push(max);
					pager.push(');return false;">');
					pager.push(txt);
					pager.push('</a>');
				}
				var pager = [];
				if(page > 1) {
					appendItem(pager, page - 1, "上一页");
				}
				for(var i = start;i <= end;i++) {
					if(i == page) {
						pager.push("<span>");
						pager.push(i);
						pager.push("</span>");
					}
					else {
						appendItem(pager, i , "[" + i + "]");
					}
				}
				if(page < max) {
					appendItem(pager, page + 1,"下一页");
				}
				html.push(pager.join(''));
				
				html.push('</div><div class="syblog_pager_footer_bar footer_bar"><span class="left"></span><span class="right"></span></div></div></div>');
			}
			$id("manager_external_comment").innerHTML = html.join('');
		});
	},
	deleteTopic: function(obj, id, p) {
		if(confirm("确实要删除该篇日志吗？")){
			var xmlhttp = new HTTPRequest();
			xmlhttp.send("/DeleteTopic.aspx","id=" + id,function(r) {
				if(p > 1 && obj.parentNode.parentNode.parentNode.childNodes.length == 3) {
					p--;
				}
				Manager.getTopicList(p);
			});
		}
	},
	deleteTrackBack: function(obj ,id, idx) {
		if(confirm("确实要删除该引用吗？")){
			var xmlhttp = new HTTPRequest();
			xmlhttp.send("/DeleteTrackBack.aspx","id=" + id + "&idx=" + idx,function(r) {
				obj.parentNode.parentNode.parentNode.removeChild(obj.parentNode.parentNode);
			});
		}
	},
	deleteComment: function(obj, id, page, idx) {
		if(confirm("确实要删除该评论吗？")){
			var xmlhttp = new HTTPRequest();
			xmlhttp.send("/DeleteComment.aspx","id=" + id + "&page=" + page + "&idx=" + idx,function(r) {
				obj.parentNode.parentNode.firstChild.innerHTML = '<span style="text-decoration:line-through">已删除</span>';
				obj.parentNode.innerHTML = "";
			});
		}
	},
	loadAlbum: function() {
		if(!window.docs.album) {
			var xmlhttp = new HTTPRequest(true,true,false);
			xmlhttp.send("/" + bloger + "/album.xml",null,function(r) {
				window.docs.album = r.getXML();
				Manager.loadAlbum();
			});
		}
		else {
			document.attachEvent("onclick", function() {
				$id("manager_album_target_container").style.visibility = "hidden";
			});
			var f = $("manager_album_form");
			$id("manager_album_list").appendChild(f.list = document.createElement("ul"));
			f.list.selectedIndex = 0;
			f.list.onchange = function(){
				var albums = window.docs.album.documentElement.selectNodes("body/a");
				f.elements["name"].value = this.childNodes[this.selectedIndex].innerText;
				var album = albums[this.selectedIndex];
				var photos = album.selectNodes("img");
				var cover = album.getAttribute("cover");
				var url = "/" + bloger + "/album/";
				if(photos.length > 0) {
					$id("manager_album_cover").src = url + "thumb/" + photos[cover].getAttribute("src");
				}
				else {
					$id("manager_album_cover").src = "/ui/img/nopic.jpg";
				}
				var html = [];
				for(var i = 0;i < photos.length;i++) {
					var src = photos[i].getAttribute("src");
					var alt = photos[i].getAttribute("alt").trim();
					if(alt.length < 1) {
						alt = decodeURI(photos[i].getAttribute("src"));
					}
					
					html.push('<div class="manager_album_photo"><a target="_blank" href="');
					html.push(url + src);
					html.push('"><img src="');
					html.push(url + "thumb/" + src);
					html.push('" /></a><div class="manager_album_photo_name"><input type="checkbox" /><a href="#" title="');
					html.push(alt.replace(/"/i, "&quot;"));
					html.push('" onclick="Manager.renamePhoto(this,', i, ');return false;">');
					html.push(alt.parseHTML());
					html.push('</a></div></div>');
				}
				$id("manager_album_photo").innerHTML = html.join('');
			}
			f.list.onclick = function() {
				if(event.srcElement.tagName == "LI" && event.srcElement.nodeIndex != this.selectedIndex) {
					this.childNodes[this.selectedIndex].className = "";
					this.childNodes[this.selectedIndex = event.srcElement.nodeIndex].className = "selected";
					this.onchange();
				}
			}
			with(f.list) {
				var albums = window.docs.album.documentElement.selectNodes("body/a");
				for(var i = 0;i < albums.length;i++) {
					var option = document.createElement("li");
					appendChild(option);
					option.nodeIndex = i;
					option.innerText = albums[i].getAttribute("name");
				}
				childNodes[0].className = "selected";
			}
			f.list.onchange();
			function createUploader() {
				var album = 0;
				var uploader = new FileUploader($id('manager_album_uploader'), "album", 638, true, 20);
				uploader.initialize();
				uploader.onUploadBefore = function(f) {
					if(f.elements.length > 1) {
						for(var i = 0;i < f.elements.length;i++) {
						    var re = new RegExp(".(jpg|jpeg|gif|png|bmp)\\s*$","i");
							if(f.elements[i].value.length > 0 && !re.test(f.elements[i].value)) {
								alert('第[' + (i + 1) + ']个图片格式无效，可接受的图片格式包括JPEG、GIF、PNG和BMP');
								return false;
							}
						}
						var t = f.ownerDocument.createElement("input");
						t.name = "album";
						album = t.value = $("manager_album_form").list.selectedIndex;
						f.appendChild(t);
						return true;
					}
					return false;
				}
				uploader.onUploadCompleted = function(filename) {
					var src = filename.substr(filename.lastIndexOf("/") + 1);
					filename = decodeURI(src);
					filename = filename.substring(0, filename.lastIndexOf('.'));
					
					var albumNode = window.docs.album.documentElement.selectNodes("body/a")[album];
					var i = albumNode.selectNodes("img").length;
					var photoNode = window.docs.album.createElement("img");
					photoNode.setAttribute("src", src);
					photoNode.setAttribute("alt", filename);
					albumNode.appendChild(photoNode);
					if(album == $("manager_album_form").list.selectedIndex) {
						var url = "/" + bloger + "/album/";
						if(photoNode.previousSibling == null) {
							$id("manager_album_cover").src = url + "thumb/" + src;
						}
						
						var photo = document.createElement("div");
						photo.className = "manager_album_photo";
						photo.innerHTML = '<a target="_blank" href="'
							+ url + src
							+ '"><img src="'
							+ url + "thumb/" + src
							+ '" /></a><div class="manager_album_photo_name"><input type="checkbox" /><a href="#" title="'
							+ filename
							+ '" onclick="Manager.renamePhoto(this,' + i + ');return false;">'
							+ filename
							+ '</a></div>';
						$id("manager_album_photo").appendChild(photo);
					}
				}
			}
			if(typeof(FileUploader) != "undefined") {
				createUploader();
			}
			else {
				ScriptLoader.Load("/js/uploader.js", createUploader);
			}
		}
	},
	setAlbum: function(f, active) {
		var idx = f.list.selectedIndex;
		var name = f.elements["name"].value.trim();
		var xmlhttp = new HTTPRequest();
		var dat = "active=" + active + "&idx=" + idx + "&name=" + encodeURIComponent(name);
		switch(true) {
			case (active == 0 && name.length > 0):
				xmlhttp.send("/SetAlbum.aspx", dat, function() {
					var option = document.createElement("li");
					f.list.childNodes[f.list.selectedIndex].className = "";
					f.list.appendChild(option);
					option.className = "selected";
					f.list.selectedIndex = option.nodeIndex = f.list.childNodes.length - 1;
					option.innerText = name;
					
					var node = window.docs.album.createElement("a");
					node.setAttribute("name", name);
					node.setAttribute("cover", "0");
					window.docs.album.documentElement.selectSingleNode("body").appendChild(node);
					
					f.list.onchange();
				});
				break;
			case (active == 1 && name.length > 0):
				xmlhttp.send("/SetAlbum.aspx", dat, function() {
					f.list.childNodes[idx].innerText = name;
					window.docs.album.documentElement.selectNodes("body/a")[idx].setAttribute("name", name);
				});
				break;
			case (active < 2 && name.length == 0):
				alert("请输入像册名称");
				break;

			case (active == 2 && idx == 0) :
				alert("不能删除默认像册");
				break;
			case (active == 2) && confirm("是否真的要删除选择的相册？删除相册后该相册里的照片将自动转移到默认相册。"):
				xmlhttp.send("/SetAlbum.aspx", dat, function() {
					var albums = window.docs.album.documentElement.selectNodes("body/a");
					var sourceAlbum = albums[idx];
					var targetAlbum = albums[0];
					var photos = sourceAlbum.selectNodes("img");
					for(var i = photos.length;i > 0;) {
						targetAlbum.appendChild(photos[--i]);
					}
					sourceAlbum.parentNode.removeChild(sourceAlbum);

					var li = f.list.childNodes[idx];
					var next = li;
					while(next = next.nextSibling) {
						next.nodeIndex -= 1;
					}
					
					if(f.list.selectedIndex == idx) {
						if(li.nextSibling) {
							li.nextSibling.className = "selected";
						}

						else {
							li.previousSibling.className = "selected";
							f.list.selectedIndex -= 1;
						}
						f.list.removeChild(li);
						f.list.onchange();
					}
					else if(f.list.selectedIndex > idx) {
						f.list.removeChild(li);
						f.list.selectedIndex -= 1;
					}
					else {
						f.list.removeChild(li);
					}
				});
				break;
			case (active == 3):
				var boxs = $id("manager_album_photo").getElementsByTagName("input");
				for(var i =0 ;i < boxs.length;i++) {
					if(boxs[i].checked) {
						var xmlhttp = new HTTPRequest();
						var list = $("manager_album_form").list;
						var idx = list.selectedIndex;
						xmlhttp.send("/SetAlbum.aspx", dat + "&cover=" + i,function() {
							var album = window.docs.album.documentElement.selectNodes("body/a")[idx];
							album.setAttribute("cover", i);
							if(list.selectedIndex == idx) {
								$id("manager_album_cover").src = "/" + bloger + "/album/" + "thumb/" + album.selectNodes("img")[i].getAttribute("src");
							}
							alert("封面设置成功");
						});
						return;
					}
				}
				alert("请选择要设为封面的图片");
				break;
			case (active == 4):
				var boxs = $id("manager_album_photo").getElementsByTagName("input");
				var photos = [];
				for(var i =0 ;i < boxs.length;i++) {
					if(boxs[i].checked) {
						photos.push(i);
					}
				}
				if(photos.length > 0 && confirm("确实要删除选择的相片吗？")) {
					var xmlhttp = new HTTPRequest();
					xmlhttp.send("/SetAlbum.aspx", dat + "&photo=" + photos.join(","), function() {
						var album = window.docs.album.documentElement.selectNodes("body/a")[idx];
						var cover = album.getAttribute("cover");				
						var nodes = album.selectNodes("img");
						
						for(var i = photos.length;i > 0;) {
							if(cover == photos[--i]) {
								album.setAttribute("cover", "0");
							}
							album.removeChild(nodes[photos[i]]);
						}
						$("manager_album_form").list.onchange();
					});
				}
				break;
		}
	},
	loadAlbumComment: function(f) {
		Manager.open('$___window___albumcomment');
		$("manager_album_title").innerHTML=$("manager_album_comment").innerHTML="";
		var album = window.docs.album.documentElement.selectNodes("body/a")[f.list.selectedIndex];
		var xmlhttp = new HTTPRequest(true,false,false);
		xmlhttp.send("/" + bloger + "/album/comment/" + album.getAttribute("id") + "/main.xml",null,function(r) {
			var pages = r.getXML().documentElement.selectNodes("body/a").length;
			$("manager_album_title").innerText = "RE:" + album.getAttribute("name") + "(" + pages + "页)";
			if(pages > 0) {
				Manager.showAlbumComment(album.getAttribute("id"), 1, pages);
			}
			else {
				$id("manager_album_comment").innerHTML = "没有评论记录";
			}
		});
	},
	showAlbumComment: function(album, page, max) {
		var xmlhttp = new HTTPRequest(true,false,false);
		xmlhttp.send("/" + bloger + "/album/comment/" + album + "/" + page + ".xml",null,function(r) {
			var comments = r.getXML().documentElement.selectNodes("body/div");
			var html = ['<div class="manager_album_comment_head"><div class="manager_album_comment_title">评论</div><div class="manager_album_comment_bloger">作者</div><div class="manager_album_comment_time">发表时间</div></div>'];
			for(var i = 0;i < comments.length;i++) {
				html.push('<div class="manager_album_comment_body"><div class="manager_album_comment_title">');
				if(comments[i].getAttribute("deleted") != null) {
					html.push('<span style="text-decoration:line-through">已删除</span>');
				}
				else {
					html.push('<span title="');
					html.push(comments[i].text.replace(/"/mg, "&quot;"));
					html.push('">');
					html.push(comments[i].text.parseHTML());
					html.push('</span>');
				}
				html.push('</div><div class="manager_album_comment_bloger">');
				if(comments[i].getAttribute("id") != null) {
					html.push('<a href="/');
					html.push(comments[i].getAttribute("id"));
					html.push('" title="');
					html.push(comments[i].getAttribute("name").replace(/"/mg, "&quot;"));
					html.push('" target="_blank">');
					html.push(comments[i].getAttribute("name").parseHTML());
					html.push('</a>');
				}
				else {
					html.push('<span title="');
					html.push(comments[i].getAttribute("name").replace(/"/mg, "&quot;"));
					html.push('">');
					html.push(comments[i].getAttribute("name").parseHTML());
					html.push('</span>');
				}
				html.push('</div><div class="manager_album_comment_time">');
				html.push(comments[i].getAttribute("time"));
				html.push('</div>');
				if(comments[i].getAttribute("deleted") == null) {
					html.push('<div class="manager_album_comment_button"><a href="#" onclick="Manager.deleteAlbumComment(this,\'');
					html.push(album + '\',' + page + ',' + i);
					html.push(');return false">删除</a></div>');
				}
				html.push('</div>');
			}
			if(max > 1) {
				html.push('<div class="syblog_pager"><div class="syblog_pager_right_bar"><div class="syblog_pager_header_bar"><span class="left"></span><span class="right"></span></div><div class="syblog_pager_content">');
					
				var start = Math.max(page - 5, 1);
				var end = Math.min(start + 5,max);
				function appendItem(pager, p, txt) {
					pager.push('<a href="#" onclick="Manager.showAlbumComment(\'');
					pager.push(album);
					pager.push("',");
					pager.push(p);
					pager.push(',');
					pager.push(max);
					pager.push(');return false;">');
					pager.push(txt);
					pager.push('</a>');
				}
				var pager = [];
				if(page > 1) {
					appendItem(pager, page - 1, "上一页");
				}
				for(var i = start;i <= end;i++) {
					if(i == page) {
						pager.push("<span>");
						pager.push(i);
						pager.push("</span>");
					}
					else {
						appendItem(pager, i , "[" + i + "]");
					}
				}
				if(page < max) {
					appendItem(pager, page + 1,"下一页");
				}
				html.push(pager.join(''));
				
				html.push('</div><div class="syblog_pager_footer_bar footer_bar"><span class="left"></span><span class="right"></span></div></div></div>');
			}
			$id("manager_album_comment").innerHTML = html.join('');
		});
	},
	deleteAlbumComment: function(obj, id, page, idx) {
		if(confirm("确实要删除该评论吗？")){
			var xmlhttp = new HTTPRequest();
			xmlhttp.send("/DeleteAlbumComment.aspx","id=" + id + "&page=" + page + "&idx=" + idx,function(r) {
				obj.parentNode.parentNode.firstChild.innerHTML = '<span style="text-decoration:line-through">已删除</span>';
				obj.parentNode.innerHTML = "";
			});
		}
	},
	checkAllPhoto: function(checked) {
		var boxs = $id("manager_album_photo").getElementsByTagName("input");
		for(var i =0 ;i < boxs.length;i++) {
			boxs[i].checked = checked;
		}
	},
	readyMovePhoto: function() {
		$id('manager_album_target_container').style.visibility = "visible";
		var albums = window.docs.album.documentElement.selectNodes("body/a");
		var idx = $("manager_album_form").list.selectedIndex;
		var html = [];
		for(var i = 0;i < albums.length;i++) {
			if(idx != i) {
				html.push('<div onclick="Manager.movePhoto(', i, ')"><span>&gt;</span> ', albums[i].getAttribute("name").parseHTML(), '</div>');
			}
		}
		$id('manager_album_target').innerHTML = html.join('');
		return event.returnValue = !(event.cancelBubble = true);
	},
	movePhoto: function(album) {
		var boxs = $id("manager_album_photo").getElementsByTagName("input");
		var photos = [];
		for(var i =0 ;i < boxs.length;i++) {
			if(boxs[i].checked) {
				photos.push(i);
			}
		}
		if(photos.length > 0) {
			var list = $id("manager_album_form").list;
			var idx = list.selectedIndex;
			var xmlhttp = new HTTPRequest();
			xmlhttp.send("/SetAlbum.aspx", "active=5&idx=" + idx + "&to=" + album + "&photo=" + photos.join(","), function() {
				var albums = window.docs.album.documentElement.selectNodes("body/a");
				var sourceAlbum = albums[idx];
				var targetAlbum = albums[album];
				
				var nodes = sourceAlbum.selectNodes("img");				
				var cover = sourceAlbum.getAttribute("cover");
				
				for(var i = photos.length;i > 0;) {
					if(photos[--i] == cover) {
						sourceAlbum.setAttribute("cover", "0");
					}
					targetAlbum.appendChild(nodes[photos[i]]);
				}
				list.onchange();
			});
		}
	},
	renamePhoto: function(obj, p) {
		var name = prompt("修改照片描述", obj.innerText);
		if(name != null && (name = name.trim()).length > 0 && name != obj.innerText) {
			var idx = $id("manager_album_form").list.selectedIndex;
			var xmlhttp = new HTTPRequest();
			xmlhttp.send("/SetAlbum.aspx", "active=6&idx=" + idx + "&photo=" + p + "&name=" + encodeURIComponent(name));
			obj.innerText = name;
			window.docs.album.documentElement.selectNodes("body/a")[idx].selectNodes("img")[p].setAttribute("alt", name);
		}
	},
	loadCollection: function() {
		if(!window.docs.collection) {
			var xmlhttp = new HTTPRequest(true,true,false);
			xmlhttp.send("/" + bloger + "/collection.xml",null,function(r) {
				window.docs.collection = r.getXML();
				Manager.loadCollection();
			});
		}
		else {
			var f = $("manager_collection_form");
			f.dom = {};
			f.item = $id("manager_collection_item");
			f.item.selectedIndex = 0;
			f.item.onchange = function() {
				var collection = f.dom.documentElement.selectNodes("body/p")[this.selectedIndex];
				with(collection.selectSingleNode("a")) {
					f.elements["title"].value = text;
					f.elements["href"].value = getAttribute("href");
				}
				f.elements["describe"].value = collection.selectSingleNode("p").text;
			}
			f.item.onclick = function() {
				if(event.srcElement.tagName == "LI" && event.srcElement.nodeIndex != this.selectedIndex) {
					this.childNodes[this.selectedIndex].className = ""
					this.childNodes[this.selectedIndex = event.srcElement.nodeIndex].className = "selected";
					this.onchange();
				}
			}
			$id("manager_collection_list").appendChild(f.list = document.createElement("ul"));
			f.list.selectedIndex = 0;
			f.list.onchange = function(){
				f.elements["name"].value = this.childNodes[this.selectedIndex].innerText;
				var href = window.docs.collection.documentElement.selectNodes("body/a")[this.selectedIndex].getAttribute("href");
				var xmlhttp = new HTTPRequest(true, false, false);
				xmlhttp.send("/" + bloger + "/" + href, null, function(r) {
					var items = (f.dom = r.getXML()).documentElement.selectNodes("body/p/a");
					f.item.innerHTML = "";
					f.item.local = href;
					
					for(var i = 0;i < items.length;i++) {
						var option = document.createElement("li");
						f.item.appendChild(option);
						option.nodeIndex = i;
						option.innerText = items[i].text;
					}
					if(!(f.elements["edit"].disabled = f.elements["delete"].disabled = !(items.length > 0))) {
						f.item.childNodes[f.item.selectedIndex = 0].className = "selected";
						f.item.onchange();
					}
				});
			}
			f.list.onclick = function() {
				if(event.srcElement.tagName == "LI" && event.srcElement.nodeIndex != this.selectedIndex) {
					this.childNodes[this.selectedIndex].className = "";
					this.childNodes[this.selectedIndex = event.srcElement.nodeIndex].className = "selected";
					this.onchange();
				}
			}
			with(f.list) {
				var collections = window.docs.collection.documentElement.selectNodes("body/a");
				for(var i = 0;i < collections.length;i++) {
					var option = document.createElement("li");
					appendChild(option);
					option.nodeIndex = i;
					option.innerText = collections[i].text;
				}
				childNodes[0].className = "selected";
			}
			f.list.onchange();
		}
	},
	setCollection: function(f, active) {
		var idx = f.list.selectedIndex;
		var name = f.elements["name"].value.trim();
		var title = f.elements["title"].value.trim();
		var href = f.elements["href"].value.trim();
		var xmlhttp = new HTTPRequest();
		var dat = "active=" + active + "&idx=" + idx + "&name=" + encodeURIComponent(name) + "&collection=" + f.item.local;
		switch(true) {
			case (active == 0 && name.length > 0):
				xmlhttp.send("/SetCollection.aspx", dat, function(r) {
					var option = document.createElement("li");
					f.list.appendChild(option);
					option.className = "selected";
					f.list.childNodes[f.list.selectedIndex].className = "";
					f.list.selectedIndex = option.nodeIndex = f.list.childNodes.length - 1;
					option.innerText = name;
					
					var node = window.docs.collection.createElement("a");
					node.setAttribute("href", r.getText());
					node.text = name;
					window.docs.collection.documentElement.selectSingleNode("body").appendChild(node);
					
					f.list.onchange();
				});
				break;
			case (active == 1 && name.length > 0):
				xmlhttp.send("/SetCollection.aspx", dat, function() {
					f.list.childNodes[idx].innerText = name;
					window.docs.collection.documentElement.selectNodes("body/a")[idx].text = name;
				});
				break;
			case (active < 2 && name.length == 0):
				alert("请输入收藏夹名称");
				break;

			case (active == 2 && idx == 0) :
				alert("不能删除默认收藏夹");
				break;
			case (active == 2) && confirm("是否真的要删除选择的收藏夹？"):
				xmlhttp.send("/SetCollection.aspx", dat, function() {
					var body = window.docs.collection.documentElement.selectSingleNode("body");
					body.removeChild(body.selectNodes("a")[idx]);
					
					var li = f.list.childNodes[idx];
					var next = li;
					while(next = next.nextSibling) {
						next.nodeIndex -= 1;
					}
					
					if(f.list.selectedIndex == idx) {
						if(li.nextSibling) {
							li.nextSibling.className = "selected";
						}

						else {
							li.previousSibling.className = "selected";
							f.list.selectedIndex -= 1;
						}
						f.list.removeChild(li);
						f.list.onchange();
					}
					else if(f.list.selectedIndex > idx) {
						f.list.removeChild(li);
						f.list.selectedIndex -= 1;
					}
					else {
						f.list.removeChild(li);
					}
				});
				break;
			case (active == 3):
				if(title.length > 0 && href.length > 0) {
					var describe = f.elements["describe"].value.trim();
					xmlhttp.send("/SetCollection.aspx", dat + "&title=" + encodeURIComponent(title) + "&href=" + encodeURIComponent(href) + "&describe=" + encodeURIComponent(describe), function() {
						var option = document.createElement("li");
						f.item.appendChild(option);
						if(0 == (option.nodeIndex = f.item.childNodes.length - 1)) {
							option.className = "selected";
							f.elements["edit"].disabled = f.elements["delete"].disabled = false;
						}
						else {
							f.item.childNodes[f.item.selectedIndex].className = "";
							f.item.selectedIndex = option.nodeIndex;
							option.className = "selected";
						}
						option.innerText = title;
						
						var node = f.dom.createElement("p");
						var lk = f.dom.createElement("a");
						lk.setAttribute("href", href);
						lk.text = title;
						node.appendChild(lk);
						
						var des = f.dom.createElement("p");
						des.text = describe;
						node.appendChild(des);
						
						f.dom.documentElement.selectSingleNode("body").appendChild(node);
					});
				}
				else {
					alert("必须输入标题和地址");
				}
				break;
			case (active == 4):
				if(title.length > 0 && href.length > 0) {
					var describe = f.elements["describe"].value.trim();
					var item = f.item.selectedIndex;
					xmlhttp.send("/SetCollection.aspx", dat + "&item=" + item + "&title=" + encodeURIComponent(title) + "&href=" + encodeURIComponent(href) + "&describe=" + encodeURIComponent(describe), function() {
						f.item.childNodes[item].innerText = title;
						
						with(f.dom.documentElement.selectNodes("body/p")[item]) {
							with(selectSingleNode("a")) {
								setAttribute("href", href);
								text = title;
							}
							selectSingleNode("p").text = describe;
						}
					});
				}
				else {
					alert("必须输入标题和地址");
				}
				break;
			case (active == 5):
				var item = f.item.selectedIndex;
				if(f.item.childNodes.length > 0) {
					xmlhttp.send("/SetCollection.aspx", dat + "&item=" + item, function() {
						var body = f.dom.documentElement.selectSingleNode("body");
						body.removeChild(body.selectNodes("p")[item]);
						
						if(f.list.selectedIndex == idx) {
							var li = f.item.childNodes[item];
							var next = li;
							while(next = next.nextSibling) {
								next.nodeIndex -= 1;
							}
							
							if(f.item.selectedIndex == item) {
								if(li.nextSibling) {
									li.nextSibling.className = "selected";
									f.item.onchange();
								}
								else if(li.previousSibling) {
									li.previousSibling.className = "selected";
									f.item.selectedIndex -= 1;
									f.item.onchange();
								}
								else {
									f.elements["edit"].disabled = f.elements["delete"].disabled = true;
								}
								f.item.removeChild(li);
							}
							else if(f.item.selectedIndex > item) {
								f.item.removeChild(li);
								f.item.selectedIndex -= 1;
							}
							else {
								f.item.removeChild(li);
							}
						}
					});
				}
				break;
		}
	},
	loadFriendLink: function() {
		var xmlhttp = new HTTPRequest(true,true,false);
		xmlhttp.send("/" + bloger + "/link.xml",null,function(r) {
			window.docs.link = r.getXML();
			
			var f = $("manager_friendlink");
			$id("manager_friendlink_list").appendChild(f.list = document.createElement("ul"));
			f.list.selectedIndex = 0;
			f.list.onchange = function(){
				var link = window.docs.link.documentElement.selectNodes("body/a")[this.selectedIndex];
				f.elements["href"].value = link.getAttribute("href");
				f.elements["title"].value = link.text;
			}
			f.list.onclick = function() {
				if(event.srcElement.tagName == "LI" && event.srcElement.nodeIndex != this.selectedIndex) {
					this.childNodes[this.selectedIndex].className = "";
					this.childNodes[this.selectedIndex = event.srcElement.nodeIndex].className = "selected";
					this.onchange();
				}
			}
			with(f.list) {
				var links = window.docs.link.documentElement.selectNodes("body/a");
				for(var i = 0;i < links.length;i++) {
					var option = document.createElement("li");
					appendChild(option);
					option.nodeIndex = i;
					option.innerText = links[i].text;
				}
				if(!(f.elements["edit"].disabled = f.elements["delete"].disabled = !(links.length > 0))) {
					childNodes[0].className = "selected";
					f.list.onchange();
				}
			}
		});
	},
	setFriendLink: function(f, active) {
		function remove(idx) {
			var body = window.docs.link.documentElement.selectSingleNode("body");
			body.removeChild(body.selectNodes("a")[idx]);
			var li = f.list.childNodes[idx];
			var next = li;
			while(next = next.nextSibling) {
				next.nodeIndex -= 1;
			}
			if(f.list.selectedIndex == idx){
				if(li.nextSibling) {
					li.nextSibling.className = "selected";
					f.list.onchange();
				}
				else if(li.previousSibling) {
					li.previousSibling.className = "selected";
					f.list.selectedIndex -= 1;
					f.list.onchange();
				}
				else {
					f.elements["edit"].disabled = f.elements["delete"].disabled = true;
				}
				f.list.removeChild(li);
			}
			else if(f.list.selectedIndex > idx) {
				f.list.selectedIndex -= 1;
				f.list.removeChild(li);
			}
			else {
				f.list.removeChild(li);
			}
		}
		var title = f.elements["title"].value.trim();
		var href = f.elements["href"].value.trim();
		var idx = f.list.selectedIndex;
		
		var dat = "active="+ active + "&idx=" + idx + "&title=" + encodeURIComponent(title) + "&href=" + encodeURIComponent(href);

		var xmlhttp = new HTTPRequest();
		var count = f.list.childNodes.length;
		
		switch(true) {
			case active < 2 && (title.length < 1 || href.length < 1) :
				alert("必须输入链接的标题和地址");
				break;
			case active == 0 && (count < 20 || confirm("友情链接数量已经达到最大限制，如果继续创建将覆盖第一个链接，确定要覆盖吗？")):
				xmlhttp.send("/SetFriendLink.aspx", dat, function(r) {
					var option = document.createElement("li");
					f.list.appendChild(option);
					option.className = "selected";
					
					if((option.nodeIndex = count) > 0) {
						f.list.childNodes[f.list.selectedIndex].className = "";
					}
					f.list.selectedIndex = option.nodeIndex;
					
					option.innerText = title;
					
					var node = window.docs.link.createElement("a");
					node.setAttribute("href", href);
					node.text = title;
					window.docs.link.documentElement.selectSingleNode("body").appendChild(node);
					f.elements["edit"].disabled = f.elements["delete"].disabled = false;
					if(count >= 20) {
						remove(0);
					}
				});
				break;
			case active == 1 :
				xmlhttp.send("/SetFriendLink.aspx", dat, function(r) {
					f.list.childNodes[idx].innerText = title;
				});
				break;
			case active == 2 :
				xmlhttp.send("/SetFriendLink.aspx", dat, function(r) {
					remove(idx);
				});
				break;
		}
	},
	loadTheme: function() {
		var xmlhttp = new HTTPRequest();
		xmlhttp.send("/ui/theme/config.xml", null, function(r) {
			window.docs.theme = r.getXML();
			
			var themeNode = window.docs.main.firstChild;
			if(themeNode.nodeName != "xml-stylesheet") {
				themeNode = themeNode.nextSibling;
			}
			
			var themeNodeText = themeNode.text || themeNode.textContent;
			var currentTheme = themeNodeText.replace(/^.*theme\/(.*)\/.*$/i, "$1").toLowerCase();
			var currentSkin = window.docs.main.documentElement.getAttribute("skin").toLowerCase();
			
			var themes = window.docs.theme.documentElement.selectNodes("theme");
			var f = $id("manager_theme_form");
			f.skin = $("manager_theme_skin");
			f.themeIndex = f.skinIndex = 0;
			f.skin.onchange = function() {
				$id("manager_theme_thumb").src = themes[f.elements["theme"].selectedIndex].selectNodes("skin")[this.selectedIndex].getAttribute("thumb");
			}
			f.skin.onclick = function() {
				if(event.srcElement.tagName == "LI" && event.srcElement.nodeIndex != this.selectedIndex) {
					this.childNodes[this.selectedIndex].className = "";
					this.childNodes[this.selectedIndex = event.srcElement.nodeIndex].className = "selected";
					this.onchange();
				}
			}
			
			f.elements["theme"].onchange = function() {
				var theme = f.elements["theme"].selectedIndex;
				var skins = themes[theme].selectNodes("skin");
				f.skin.innerHTML = "";
				f.skin.selectedIndex = 0;
				
				for(var i = 0;i < skins.length;i++) {
					var option = document.createElement("li");
					f.skin.appendChild(option);
					option.nodeIndex = i;
					option.innerText = skins[i].text;
				}
				
				if(f.themeIndex == theme) {
					f.skin.selectedIndex = f.skinIndex;
				}
				
				f.skin.childNodes[f.skin.selectedIndex].className = "selected";
				f.skin.onchange();
			}
			with($(f.elements["theme"])) {
				options.length = themes.length;
				for(var i = 0;i < themes.length;i++) {
					options[i].text = themes[i].getAttribute("name");
					if((options[i].value = themes[i].getAttribute("id").toLowerCase()) == currentTheme) {
						f.themeIndex = i;
					}
				}
				var skins = themes[f.themeIndex].selectNodes("skin");
				for(var i = 0;i < skins.length;i++) {
					if(skins[i].getAttribute("id").toLowerCase() == currentSkin) {
						f.currentIndex = i;
						break;
					}
				}
			}
			f.elements["theme"].onchange();
		});
	},
	setTheme: function(f) {
		var theme = f.elements["theme"].selectedIndex;
		var skin = f.skin.selectedIndex;
		var xmlhttp = new HTTPRequest();
		xmlhttp.send("/SetTheme.aspx", "theme=" + f.elements["theme"].value + "&skin=" + window.docs.theme.documentElement.selectNodes("theme")[theme].selectNodes("skin")[skin].getAttribute("id"), function(r) {
			f.themeIndex = theme;
			f.skinIndex = skin;
			if(confirm("主题设置保存成功，刷新后方可看到实际效果。\n现在刷新吗?")) {
				location.reload();
			}
		});
	},
	loadModule: function() {
		var xmlhttp = new HTTPRequest(true,true,false);
		xmlhttp.send("/" + bloger + "/main.xml",null,function(r) {
			window.docs.main = r.getXML();
			var f = $id("manager_module_form");
			
			$id("manager_module_list").appendChild(f.list = document.createElement("ul"));			
			f.list.selectedIndex = 0;
			f.list.onchange = function() {
				var module = window.docs.main.documentElement.selectNodes("body/a")[this.selectedIndex];
				f.elements["title"].value = module.getAttribute("title");
				f.elements["display"][1 - module.getAttribute("display")].checked = true;
				f.elements["position"][module.getAttribute("position")].checked = true;
				if(module.getAttribute("id") == "custom") {
					Manager.modulePreview(f.elements["body"].value = module.text);
				}
				else {
					Manager.modulePreview(f.elements["body"].value = "");
				}
			}
			f.list.onclick = function() {
				if(event.srcElement.tagName == "LI" && event.srcElement.nodeIndex != this.selectedIndex) {
					this.childNodes[this.selectedIndex].removeClassName("selected");
					this.childNodes[this.selectedIndex = event.srcElement.nodeIndex].appendClassName("selected");
					this.onchange();
				}
			}
			with(f.list) {
				var modules = window.docs.main.documentElement.selectNodes("body/a");
				for(var i = 0;i < modules.length;i++) {
					var option = $(document.createElement("li"));
					appendChild(option);
					option.nodeIndex = i;
					option.innerText = modules[i].getAttribute("title");
					if(modules[i].getAttribute("id").toLowerCase() == "custom") {
						option.className = "custom";
					}
					if(modules[i].getAttribute("display") != 1) {
						option.appendClassName("disabled");
					}
				}
				childNodes[0].appendClassName("selected");
			}
			f.list.onchange();
		});
	},
	modulePreview: function(txt, isCustom) {
		function preview(body, ticket) {
			var container = $id("manager_custom_module");
			container.innerHTML = "&nbsp;";
			container.innerHTML = '<iframe class="manager_custom_module"></iframe>';
			var doc = container.firstChild.contentWindow.document;
			var node = window.docs.main.documentElement
			var html = '<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><link rel="stylesheet" type="text/css" href="'
				+ "/ui/theme/{0}/skin/{1}/".format(window.docs.main.documentElement.getAttribute("theme"),window.docs.main.documentElement.getAttribute("skin"))
				+ 'style.css" /><style type="text/css">body{padding-top:10px;overflow:scroll;overflow-x:hidden}</style>'
				+ '</head><body><div class="syblog_middle_left"><dl class="syblog_module_custom"><dt><span>预览</span></dt><dd class="syblog_list_item"><div class="syblog_module_custom_container">'
				+ body
				+ '</dd><dd class="syblog_list_footer"></dd></dl></div><div style="clear:both"></div>'
				+ '<scr' + 'ipt type="text/javascript">if(parent.Manager.task){parent.Manager.task("' + ticket + '");}</scr' + 'ipt>'
				+ '</body></html>';
			doc.write(html);
		}
		if(isCustom) {
			var xmlhttp = new HTTPRequest(true, true, false);
			xmlhttp.send("/IssueTicket.aspx", null, function(r){
				preview(txt.replace(/(<script[^>]*[\s\/]+)(defer)(.*>)/i,"$1_defer$3"), r.getText());
			});
		}
		else {
			preview(txt, 0);
		}
	},
	setModule: function(f, active) {
		var idx = f.list.selectedIndex;
		var title = f.elements["title"].value.trim();
		var dat = "active=" + active + "&idx=" + idx;
		
		var display = (f.elements["display"][0].checked ? 1 : 0);
		var position = (f.elements["position"][0].checked ? 0 : ((f.elements["position"][1].checked ? 1 : 2)));
		var body = f.elements["body"].value.trim();
		
		var xmlhttp = new HTTPRequest();
		switch(true) {
			case active == "5":
				Manager.modulePreview(f.elements["body"].value);
				break;
			case active == 3 && idx > 0:
				xmlhttp.send("/SetModule.aspx", dat, function(r) {
					var module = window.docs.main.documentElement.selectNodes("body/a")[idx];
					module.parentNode.insertBefore(module, module.previousSibling);
					
					f.list.childNodes[idx].nodeIndex -= 1;
					f.list.childNodes[idx - 1].nodeIndex += 1;
					f.list.childNodes[idx - 1].insertAdjacentElement("beforeBegin", f.list.childNodes[idx]);
					
					if(f.list.selectedIndex == idx) {
						f.list.selectedIndex -= 1;
					}
					else if(f.list.selectedIndex == idx - 1) {
						f.list.selectedIndex += 1;
					}
				});
				break;
			case active == 4 && f.list.childNodes[idx].nextSibling != null:
				xmlhttp.send("/SetModule.aspx", dat, function(r) {					
					var module = window.docs.main.documentElement.selectNodes("body/a")[idx];
					module.parentNode.insertBefore(module.nextSibling, module);
					
					f.list.childNodes[idx].nodeIndex += 1;
					f.list.childNodes[idx + 1].nodeIndex -= 1;
					f.list.childNodes[idx].insertAdjacentElement("beforeBegin", f.list.childNodes[idx + 1]);
					
					if(f.list.selectedIndex == idx) {
						f.list.selectedIndex += 1;
					}
					else if(f.list.selectedIndex == idx + 1) {
						f.list.selectedIndex -= 1;
					}
				});
				break;
			case active < 2 && title.length == 0:
				alert("请输入模块名称");
				break;
			case active == 0:
				dat = dat + "&title=" + encodeURIComponent(title) + "&display=" + display + "&position=" + position + "&body=" + encodeURIComponent(body);
				Manager.task = function(ticket) {
					Manager.task = null;
					xmlhttp.send("/SetModule.aspx", dat + "&ticket=" + ticket, function(r) {
						var node = window.docs.main.createElement("a");
						node.setAttribute("id", "custom");
						node.setAttribute("title", title);
						node.setAttribute("display", display);
						node.setAttribute("position", position);
						node.text = body;
						window.docs.main.documentElement.selectSingleNode("body").appendChild(node);
						
						var module = $(document.createElement("li"));
						f.list.appendChild(module);
						module.nodeIndex = f.list.childNodes.length - 1;
						module.innerText = title;
						module.className = "custom";
						if(!display) {
							module.appendClassName("disabled");
						}
						if(f.list.selectedIndex == idx) {
							f.list.childNodes[f.list.selectedIndex].removeClassName("selected");
							f.list.childNodes[f.list.selectedIndex = module.nodeIndex].appendClassName("selected");
						}
					});
				};
				Manager.modulePreview(body, true);
				break;
			case active == 1:
				var node = window.docs.main.documentElement.selectNodes("body/a")[idx];
				dat = dat + "&title=" + encodeURIComponent(title) + "&display=" + display + "&position=" + position + "&body=" + encodeURIComponent(body);
				var isCustom = (node.getAttribute("id").toLowerCase() == "custom");
				Manager.task = function(ticket) {
					Manager.task = null;
					xmlhttp.send("/SetModule.aspx", dat + "&ticket=" + ticket, function(r) {
						node.setAttribute("title", title);
						node.setAttribute("display", display);
						node.setAttribute("position", position);
						if(isCustom) {
							node.text = body;
						}
						var module = f.list.childNodes[idx];
						module.innerText = title;
						if(!display) {
							module.appendClassName("disabled");
						}
						else {
							module.removeClassName("disabled");
						}
					});
				};
				Manager.modulePreview(body, isCustom);
				break;
			case active == 2:
				var node = window.docs.main.documentElement.selectNodes("body/a")[idx];
				if(node.getAttribute("id").trim().toLowerCase() != "custom") {
					alert("不能删除系统模块");
				}
				else {
					xmlhttp.send("/SetModule.aspx", dat, function(r) {
						node.parentNode.removeChild(node);
						var li = f.list.childNodes[idx];
						var next = li;
						while(next = next.nextSibling) {
							next.nodeIndex -= 1;
						}
						
						if(f.list.selectedIndex == idx) {
							if(li.nextSibling) {
								li.nextSibling.appendClassName("selected");
							}

							else {
								li.previousSibling.appendClassName("selected");
								f.list.selectedIndex -= 1;
							}
							f.list.removeChild(li);
							f.list.onchange();
						}
						else if(f.list.selectedIndex > idx) {
							f.list.removeChild(li);
							f.list.selectedIndex -= 1;
						}
						else {
							f.list.removeChild(li);
						}
					});
				}
				break;
		}
	},
	loadStyleSheet: function() {
		var xmlhttp = new HTTPRequest(true, true, false);
		xmlhttp.send("/" + bloger + "/style.css", null, function(r) {
			$("manager_style_form").elements["styletext"].value = r.getText();
		});
	},
	loadBlogInfo: function() {
		var f = $("manager_bloginfo_form");
		f.elements["title"].value = document.XMLDocument.documentElement.selectSingleNode("head/title").text;
		f.elements["description"].value = document.XMLDocument.documentElement.selectSingleNode("head/meta[@name='description']").getAttribute("content");
		$id("manager_bloginfo_face").innerHTML = '<img src="' + document.XMLDocument.documentElement.selectSingleNode("head/meta[@name='author']").getAttribute("head") + '" />';
		function createUploader() {
			var uploader = new FileUploader($id('manager_bloginfo_uploader'), "face", 420, false);
			uploader.initialize();
			uploader.onUploadBefore = function(f) {
				if(f.elements[0].value.length > 0) {
					if((new RegExp(".(jpg|jpeg|gif|png|bmp)\\s*$","i")).test(f.elements[0].value)) {
						return true;
					}
					else {
						alert("无效的图片文件，可接受的图片格式包括JPEG、GIF、PNG和BMP");
					}
				}
				return false;
			}
			uploader.onUploadCompleted = function(filename) {
				with($id("manager_bloginfo_face")) {
					innerHTML = "&nbsp;";
					innerHTML = '<img src="/' + bloger + '/face/' + decodeURI(filename.substr(filename.lastIndexOf("/") + 1)) + '" />';
				}
			}
		}
		if(typeof(FileUploader) != "undefined") {
			createUploader();
		}
		else {
			ScriptLoader.Load("/js/uploader.js", createUploader);
		}
	},
	updateOtherBirthBox: function(f) {
		var lunarInfo = [0x04bd8,0x04ae0,0x0a570,0x054d5,0x0d260,0x0d950,0x16554,0x056a0,0x09ad0,0x055d2,
				0x04ae0,0x0a5b6,0x0a4d0,0x0d250,0x1d255,0x0b540,0x0d6a0,0x0ada2,0x095b0,0x14977,
				0x04970,0x0a4b0,0x0b4b5,0x06a50,0x06d40,0x1ab54,0x02b60,0x09570,0x052f2,0x04970,
				0x06566,0x0d4a0,0x0ea50,0x06e95,0x05ad0,0x02b60,0x186e3,0x092e0,0x1c8d7,0x0c950,
				0x0d4a0,0x1d8a6,0x0b550,0x056a0,0x1a5b4,0x025d0,0x092d0,0x0d2b2,0x0a950,0x0b557,
				0x06ca0,0x0b550,0x15355,0x04da0,0x0a5b0,0x14573,0x052b0,0x0a9a8,0x0e950,0x06aa0,
				0x0aea6,0x0ab50,0x04b60,0x0aae4,0x0a570,0x05260,0x0f263,0x0d950,0x05b57,0x056a0,
				0x096d0,0x04dd5,0x04ad0,0x0a4d0,0x0d4d4,0x0d250,0x0d558,0x0b540,0x0b6a0,0x195a6,
				0x095b0,0x049b0,0x0a974,0x0a4b0,0x0b27a,0x06a50,0x06d40,0x0af46,0x0ab60,0x09570,
				0x04af5,0x04970,0x064b0,0x074a3,0x0ea50,0x06b58,0x055c0,0x0ab60,0x096d5,0x092e0,
				0x0c960,0x0d954,0x0d4a0,0x0da50,0x07552,0x056a0,0x0abb7,0x025d0,0x092d0,0x0cab5,
				0x0a950,0x0b4a0,0x0baa4,0x0ad50,0x055d9,0x04ba0,0x0a5b0,0x15176,0x052b0,0x0a930,
				0x07954,0x06aa0,0x0ad50,0x05b52,0x04b60,0x0a6e6,0x0a4e0,0x0d260,0x0ea65,0x0d530,
				0x05aa0,0x076a3,0x096d0,0x04bd7,0x04ad0,0x0a4d0,0x1d0b6,0x0d250,0x0d520,0x0dd45,
				0x0b5a0,0x056d0,0x055b2,0x049b0,0x0a577,0x0a4b0,0x0aa50,0x1b255,0x06d20,0x0ada0,
				0x14b63];
		var sTermInfo = [0,21208,42467,63836,85337,107014,128867,150921,173149,195551,218072,240693,263343,285989,308563,331033,
				353350,375494,397447,419210,440795,462224,483532,504758];
				
		var anims = ["鼠","牛","虎","兔","龙","蛇","马","羊","猴","鸡","狗","猪"];
		var constellation = ["摩羯座","水瓶座","双鱼座","白羊座","金牛座","双子座","巨蟹座","狮子座","处女座","天秤座","天蝎座","射手座","摩羯座"];
		var conintersecte = [20,19,21,20,21,21,22,23,23,23,22,22];
		var gan = ["甲","乙","丙","丁","戊","己","庚","辛","壬","癸"];
		var zhi = ["子","丑","寅","卯","辰","巳","午","未","申","酉","戌","亥"];
		var lunarMonths = ['正','二','三','四','五','六','七','八','九','十','十一','十二'];
		var nStr1 = ['日','一','二','三','四','五','六','七','八','九','十'];
		var nStr2 = ['初','十','廿','卅','　'];
		
		function sTerm (y,n) {
			var offDate=new Date((31556925974.7*(y-1900) + sTermInfo[n]*60000)+Date.UTC(1900,0,6,2,5));
			return(offDate.getUTCDate());
		}
		function cyclical(num) {
			return gan[num%10] + zhi[num%12];
		}
		function leapMonth(y) {
			return lunarInfo[y-1900] & 0xf;
		}
		function leapDays(y) {
			if(leapMonth(y)){
				return (lunarInfo[y-1900] & 0x10000)? 30: 29;
			}
			else {
				return 0;
			}
		}
		function lYearDays(y) {
			var i, sum = 348
			for(i=0x8000; i>0x8; i>>=1) {
				sum += (lunarInfo[y-1900] & i)? 1: 0;
			}
			return sum+leapDays(y);
		}
		function monthDays(y,m) {
			return (lunarInfo[y-1900] & (0x10000>>m))? 30: 29;
		}
		function Lunar(y, m, d) {
			var i, leap=0, temp=0;
			var date = Date.UTC(y,m,d);
			var baseDate = Date.UTC(1900,0,31);
			var offset = (date - baseDate) / 86400000;
			this.dayCyl = offset + 40;
			this.monCyl = d < sTerm(y,m * 2) ? 13 : 14;
			for(i=1900; i<2050 && offset>0; i++) {
				temp = lYearDays(i);
				offset -= temp;
				this.monCyl += 12;
			}
			if(offset<0) {
				offset += temp;
				i--;
				this.monCyl -= 12
			}
			this.year = i;
			this.yearCyl = i-1864;
		
			leap = leapMonth(i);
			this.isLeap = false;
		
			for(i=1; i<13 && offset>0; i++) {;
				if(leap>0 && i==(leap+1) && this.isLeap==false) {
					--i;
					this.isLeap = true;
					temp = leapDays(this.year);
				}
				else {
					temp = monthDays(this.year, i);
				};
				if(this.isLeap && i==(leap+1)) {
					this.isLeap = false;
				}
		
				offset -= temp;
				if(!this.isLeap) {
					this.monCyl++;
				}
			}
		
			if(offset==0 && leap>0 && i==leap+1) {
				if(this.isLeap) {
					this.isLeap = false;
				}
				else {
					this.isLeap = true;
					--i;
					--this.monCyl;
				}
			}
			if(offset<0) {
				offset += temp;
				--i;
				--this.monCyl;
			}

			this.month = i;
			this.day = offset + 1;
		}
		function cDay(m,d){
			var s = lunarMonths[m - 1] + '月';
			switch (d) {
				case 10:
					s += '初十';
					break;
				case 20:
					s += '二十';
					break;
				case 30:
					s += '三十';
					break;
				default:
					s += nStr2[Math.floor(d/10)];
					s += nStr1[d%10];
					break;
			}
			return(s);
		}
		var m = f.elements["month"].selectedIndex;
		var d = f.elements["day"].value;
		var lDate = new Lunar(f.elements["year"].value, m , d);
		f.elements["birthday"].value = cyclical(lDate.yearCyl) + '年'+cDay(lDate.month, lDate.day);
		f.elements["aniproto"].value = zhi[lDate.yearCyl % 12] + anims[lDate.yearCyl % 12];
		f.elements["constellation"].value = constellation[m + (d < conintersecte[m] ? 0 : 1)];
	},
	updateBirthBox: function(f) {
		var year = f.elements["year"].value;
		var month = f.elements["month"].selectedIndex;
		var day = [31,28,31,30,31,30,31,31,30,31,30,31][month];
		if(month == 1 && ((year % 4 == 0 && year % 100 > 0) || year % 400 == 0)) {
			day=29;
		}
		with($(f.elements["day"])) {
			if(selectedIndex >= day) {
				selectedIndex = day -1;
			}
			options.length = day;
			for(var i = 0;i < day;) {
				options[i].value = options[i].text = ++i;
			}
		}
		f.elements["day"].onchange();
	},
	loadUserInfo: function() {
		$("manager_userinfo_form").elements["name"].value = document.XMLDocument.documentElement.selectSingleNode("head/meta[@name='author']").getAttribute("content");
		var img = $id("manager_userinfo_head").innerHTML = '<img src="/' + bloger + '/head/" />';
		function createUploader() {
			var uploader = new FileUploader($id('manager_userinfo_uploader'), "head", 390, false);
			uploader.initialize();
			uploader.onUploadBefore = function(f) {
				if(f.elements[0].value.length > 0) {
					if((new RegExp(".(jpg|jpeg|gif|png)\\s*$","i")).test(f.elements[0].value)) {
						return true;
					}
					else {
						alert("无效的头像文件格式，可接受的图片格式包括JPEG、GIF和PNG");
					}
				}
				return false;
			}
			uploader.onUploadCompleted = function(filename) {
				with($id("manager_userinfo_head")) {
					innerHTML = "&nbsp;";
					innerHTML = '<img src="/' + bloger + '/head/?' + (new Date()).getTime() + '" />';
				}
			}
		}
		function bindBirthBox(f) {
			var start = (new Date()).getFullYear() - 99;
			with($(f.elements["year"])) {
				options.length = 100;
				for(var i = 0;i < 100;i++) {
					options[i].value = options[i].text = start++;
				}
				selectedIndex = 80;
			}
			f.elements["year"].onchange();
		}
		function bindDrapDownList(f, fields) {
			for(var i = 0;i < fields.length;i++) {
				var opts = this.consts[fields[i][1]];
				with($(f.elements[fields[i][0]])) {
					options.length = opts.length;
					for(var j = 0;j < opts.length;j++) {
						options[j].value = opts[j].id;
						options[j].text = opts[j].name;
					}
					selectedIndex = 0;
				}
				if($(f.elements[fields[i][0]]).onchange) {
					$(f.elements[fields[i][0]]).onchange();
				}
			}
		}
		function bindCheckGroup(fields) {
			for(var i = 0;i < fields.length;i++) {
				var html = [];
				var id = fields[i];
				var opts = this.consts[id];
				for(var j = 0;j < opts.length;j++) {
					html.push('<div><input type="checkbox" name="');
					html.push(id);
					html.push('" id="manager_userinfo_');
					html.push(id);
					html.push(j);
					html.push('" value="');
					html.push(opts[j].id);
					html.push('" />');
					html.push('<label for="manager_userinfo_');
					html.push(id);
					html.push(j);
					html.push('">');
					html.push(opts[j].name.parseHTML());
					html.push('</label></div>');
				}
				$id("manager_userinfo_" + id).innerHTML = html.join('');
			}
		}
		function loadUserDetail(f) {
			var xmlhttp = new HTTPRequest(true, false, false);
			xmlhttp.send("/" + bloger + "/info.xml", null, function(r) {
				var doc = r.getXML().documentElement.selectSingleNode("body");
				f.elements["other_character"].value = doc.selectNodes("p[@id='character']/span")[2].text;
				f.elements["other_hobby"].value = doc.selectNodes("p[@id='hobby']/span")[2].text;
				f.elements["gender"][doc.selectNodes("p[@id='gender']/span")[1].getAttribute("title")].checked = true;
				var birthday = new Date(doc.selectNodes("p[@id='birthday']/span")[1].text);
				with(f.elements["year"]) {
					value = birthday.getFullYear();
					if(selectedIndex < 0) {
						selectedIndex = 80;
					}
				}
				f.elements["day"].value = birthday.getDate();
				f.elements["day"].onchange();
				
				var fields = [["realname","realname"], ["birthday","birthday2"], ["aniproto","aniproto"], ["constellation","constellation"], ["resume","resume"], ["height","height"], ["weight","weight"], ["school","school"], ["speciality","speciality"], ["sport","sport"], ["book","book"], ["music","music"], ["movie","movie"], ["star","star"], ["address","address"], ["postcode","postcode"], ["phone","phone"], ["email","email"], ["msn","msn"], ["qq","qq"], ["skype","skype"], ["contact","contact"]];
				for(var i = 0;i < fields.length;i++) {
					f.elements[fields[i][0]].value = doc.selectNodes("p[@id='" + fields[i][1] + "']/span")[1].text;
				}
				fields = ["people","blood","marital","smoke","drink","salary","knowledge","marital"];
				for(var i = 0;i < fields.length;i++) {
					with(f.elements[fields[i]]) {
						value = doc.selectNodes("p[@id='" + fields[i] + "']/span")[1].getAttribute("title");
					}
				}
				fields = [["oprovince","ocity"],["province","city"],["industry","occupation"]];
				for(var i = 0;i < fields.length;i++) {
					var node = doc.selectNodes("p[@id='" + fields[i][0] + "']/span");
					f.elements[fields[i][0]].value = node[1].getAttribute("title");
					f.elements[fields[i][0]].onchange();
					f.elements[fields[i][1]].value = node[2].getAttribute("title");
				}
				fields = ["character","hobby"];
				for(var i = 0;i < fields.length;i++) {
					var str = doc.selectNodes("p[@id='" + fields[i] + "']/span")[1].getAttribute("title");
					if(str.length > 0) {
						var values = str.split(",");
						var boxs = f.elements[fields[i]];
						for(var j = 0;j < values.length;j++) {
							boxs[values[j]].checked = true;
						}
					}
				}
			});
		}
		if(typeof(FileUploader) != "undefined") {
			createUploader();
		}
		else {
			ScriptLoader.Load("/js/uploader.js", createUploader);
		}
		var f = $("manager_userinfo_detail");
		bindDrapDownList.bind(this)(f,[["people","people"],["oprovince","province"],["province","province"],["blood","blood"],["marital","marital"],["smoke","smoke"],["drink","drink"],["industry","industry"],["salary","salary"],["knowledge","knowledge"]]);
		bindCheckGroup.bind(this)(["character","hobby"]);
		bindBirthBox(f);
		loadUserDetail(f);
	},
	loadFriendset: function() {
		var xmlhttp = new HTTPRequest();
		xmlhttp.send("/DataReader.aspx?ds=friendset", "u=" + bloger, function(r) {
			$("manager_friendset_form").elements["set"][r.getXML().documentElement.selectSingleNode("table/row/friendset").text].checked = true;
		});
	},
	loadFriendList: function() {
		var xmlhttp = new HTTPRequest();
		xmlhttp.send("/DataReader.aspx?ds=mfriend", "u=" + bloger, function(r) {
			var html = [];
			var friends = r.getXML().documentElement.selectNodes("table/row");
			for(var i =0;i < friends.length;i++) {
				html.push('<p><input type="checkbox" name="friend" value="');
				html.push(friends[i].selectSingleNode("id").text);
				html.push('"><img src="/ui/img/bloger_card_icon.gif" onclick="showCard(this)" alt="');
				html.push(friends[i].selectSingleNode("account").text);
				html.push('" title="');
				html.push(friends[i].selectSingleNode("name").text.replace(/"/mg, '&quot;'));
				html.push('" /><a target="_blank" href="/');
				html.push(friends[i].selectSingleNode("account").text);
				html.push('">');
				html.push(friends[i].selectSingleNode("name").text.parseHTML());
				html.push('</a></p>');
			}
			$id("manager_friend_list").innerHTML = html.join('');
		});
	},
	selectFriend: function(f,check) {
		var friends = $id("manager_friend_list").getElementsByTagName("input");
		for(var i = 0;i < friends.length;i++) {
			friends[i].checked = check;
		}
	},
	deleteFriend: function(f) {
		var deletes = [];
		var friends = $id("manager_friend_list").getElementsByTagName("input");
		for(var i = 0;i < friends.length;i++) {
			if(friends[i].checked) {
				deletes.push(friends[i].parentNode);
			}
		}
		if(deletes.length > 0) {
			$(f).post(function(r){
				for(var i = deletes.length; i > 0;) {
					deletes[--i].parentNode.removeChild(deletes[i]);
				}
			});
		}
	},
	loadInviteList: function() {
		var xmlhttp = new HTTPRequest();
		xmlhttp.send("/DataReader.aspx?ds=invitelist", "u=" + bloger, function(r) {
			var html = [];
			var friends = r.getXML().documentElement.selectNodes("table/row");
			for(var i =0;i < friends.length;i++) {
				html.push('<p><input type="checkbox" name="invite" value="');
				html.push(friends[i].selectSingleNode("id").text);
				html.push('"><img src="/ui/img/bloger_card_icon.gif" onclick="showCard(this)" alt="');
				html.push(friends[i].selectSingleNode("account").text);
				html.push('" title="');
				html.push(friends[i].selectSingleNode("name").text.replace(/"/mg, '&quot;'));
				html.push('" /><a target="_blank" href="/');
				html.push(friends[i].selectSingleNode("account").text);
				html.push('">');
				html.push(friends[i].selectSingleNode("name").text.parseHTML());
				html.push('</a><layer>——');
				html.push(friends[i].selectSingleNode("invitetime").text);
				html.push('</layer><span>');
				html.push(friends[i].selectSingleNode("remark").text.parseHTML());
				html.push('</span></p>');
			}
			$id("manager_invite_list").innerHTML = html.join('');
		});
	},
	selectInvite: function(f,check) {
		var friends = $id("manager_invite_list").getElementsByTagName("input");
		for(var i = 0;i < friends.length;i++) {
			friends[i].checked = check;
		}
	},
	deleteInvite: function(f, res) {
		f.elements["result"].value = res;
		var deletes = [];
		var friends = $id("manager_invite_list").getElementsByTagName("input");
		for(var i = 0;i < friends.length;i++) {
			if(friends[i].checked) {
				deletes.push(friends[i].parentNode);
			}
		}
		if(deletes.length > 0) {
			$(f).post(function(r){
				for(var i = deletes.length; i > 0;) {
					deletes[--i].parentNode.removeChild(deletes[i]);
					if($id("manager_friend_list") != null) {
						Manager.loadFriendList();
					}
				}
			});
		}
	},
	getLeave: function(p) {
		var list = $id("manager_leave_list");
		var xmlhttp = new HTTPRequest();
		if(!list.styleshheet) {
			xmlhttp.send("/ui/common/m-leave-list.xsl", null, function(r) {
				list.styleshheet = r.getXML();
				Manager.getLeave(p);
			});
		}
		else {
			list.page = p;
			var data = "u=" + bloger + "&s=20&p=" + p;
			xmlhttp.send("/DataReader.aspx?ds=mleave", data, function(r) {
				var leave = r.getXML();
				list.pagecount = Math.ceil(leave.documentElement.selectSingleNode("table/row/count").text / leave.documentElement.getAttribute("s"));
				list.innerHTML = leave.transformNode(list.styleshheet);
			});
		}
	},
	selectLeave: function(f,check) {
		var leaves = $id("manager_leave_list").getElementsByTagName("input");
		for(var i = 0;i < leaves.length;i++) {
			leaves[i].checked = check;
		}
	},
	deleteLeave: function(f) {
		var deletes = [];
		var list = $id("manager_leave_list");
		var leaves = list.getElementsByTagName("input");
		for(var i = 0;i < leaves.length;i++) {
			if(leaves[i].checked) {
				deletes.push(leaves[i].parentNode);
			}
		}
		if(deletes.length > 0) {
			$(f).post(function(r){
				if(deletes.length == leaves.length && list.page > 1 && list.pagecount == list.page) {
					list.page -= 1;
				}
				if(list.pagecount != list.page) {
				    Manager.getLeave(list.page);
				} else {
					for(var i = 0;i < deletes.length;i++) {
						deletes[i].parentNode.removeChild(deletes[i]);
					}
				}
			});
		}
	},
	getMessage: function(p) {
		var xmlhttp = new HTTPRequest();
		var list = $id("manager_message_list");
		if(!list.styleshheet) {
			xmlhttp.send("/ui/common/m-message-list.xsl", null, function(r) {
				list.styleshheet = r.getXML();
				Manager.getMessage(p);
			});
		}
		else {
			list.page = p;
			var data = "t=false&s=20&p=" + p;
			xmlhttp.send("/GetMessage.aspx", data, function(r) {
				var message = r.getXML();
				list.pagecount = Math.ceil(message.documentElement.selectSingleNode("table/row/count").text / message.documentElement.getAttribute("s"));
				list.innerHTML = message.transformNode(list.styleshheet);
			});
		}
	},
	selectMessage: function(f,check) {
		var messages = $id("manager_message_list").getElementsByTagName("input");
		for(var i = 0;i < messages.length;i++) {
			messages[i].checked = check;
		}
	},
	deleteMessage: function(f) {
		var deletes = [];
		var list = $id("manager_message_list");
		var messages = list.getElementsByTagName("input");
		for(var i = 0;i < messages.length;i++) {
			if(messages[i].checked) {
				deletes.push(messages[i].parentNode);
			}
		}
		if(deletes.length > 0) {
			$(f).post(function(r){
				if(deletes.length == messages.length && list.page > 1 && list.pagecount == list.page) {
					list.page -= 1;
				}
				if(list.pagecount != list.page) {
				    Manager.getMessage(list.page);
				} else {
				    for(var i = 0;i < deletes.length;i++) {
					    deletes[i].parentNode.removeChild(deletes[i]);
				    }
				}
			});
		}
	},
	getSysMessage: function(p) {
		var xmlhttp = new HTTPRequest();
		var list = $id("manager_sysmessage_list");
		if(!list.styleshheet) {
			xmlhttp.send("/ui/common/m-sysmessage-list.xsl", null, function(r) {
				list.styleshheet = r.getXML();
				Manager.getSysMessage(p);
			});
		}
		else {
			list.page = p;
			var data = "t=true&s=20&p=" + p;
			xmlhttp.send("/GetMessage.aspx", data, function(r) {
				var message = r.getXML();
				list.pagecount = Math.ceil(message.documentElement.selectSingleNode("table/row/count").text / message.documentElement.getAttribute("s"));
				list.innerHTML = message.transformNode(list.styleshheet);
			});
		}
	},
	selectSysMessage: function(f,check) {
		var messages = $id("manager_sysmessage_list").getElementsByTagName("input");
		for(var i = 0;i < messages.length;i++) {
			messages[i].checked = check;
		}
	},
	deleteSysMessage: function(f) {
		var deletes = [];
		var list = $id("manager_sysmessage_list");
		var messages = list.getElementsByTagName("input");
		for(var i = 0;i < messages.length;i++) {
			if(messages[i].checked) {
				deletes.push(messages[i].parentNode);
			}
		}
		if(deletes.length > 0) {
			$(f).post(function(r){
				if(deletes.length == messages.length && list.page > 1 && list.pagecount == list.page) {
					list.page -= 1;
				}
				if(list.pagecount != list.page) {
				    Manager.getSysMessage(list.page);
				} else {
				    for(var i = 0;i < deletes.length;i++) {
					    deletes[i].parentNode.removeChild(deletes[i]);
				    }
				}
			});
		}
	}
}